#!/usr/bin/python

import string, UserDict

# Notes:
# * new_instance = instance.copy doesn't work correctly right now.  UserDict
#   wants the class to take a dictionary upon init, but I'd rather take a 
#   location.  E-mail me if you have a good solution to this...
# * Any comments in the .INI file will be lost!  Doing a .save will overwrite 
#   the file.  Sorry.  Thinking about a fix for this...

__version__ = "0.8"

class ini_file(UserDict.UserDict):
    def __init__(self, location = ""):
        self.data = {}
        self.autosave = 0
        if location:
            self.location = location
            self.parse_file()

    def parse_file(self):
        file_obj = open(self.location, 'r')
        file_list = file_obj.readlines()
        loc = 0
        cur_fam = ""
        cur_data = ""
        cur_field = ""
        for l in file_list:
            l = string.strip(l)
            if len(l) > 0:
                if (l[0] == "["):
                    loc = string.find(l, "]")
                    cur_fam = l[1:loc]
                    self.data[cur_fam] = {}
                elif (l[0] in string.letters) or (l[0] in string.digits):
                    loc = string.find(l, "=")
                    cur_field = l[0:loc]
                    cur_data = l[loc+1:]
                    self.data[cur_fam][cur_field] = cur_data
        file_obj.close()
        
    def GetProfileString(self, family, field):
        try:
            return self.data[family][field]
        except KeyError, key_not_found:
            x_err = '"%s" not found in ini file/object.' % key_not_found
            raise KeyError, x_err

    def SetProfileString(self, family, field, info):
        # SPS *will* create a new entry with the info given.
        if not self.data.has_key(family):
            self.data[family] = {}
        self.data[family][field] = info
        if self.autosave:
            self.save()

    def save(self):
        file_obj = open(self.location, 'w')
        fam_list = self.data.keys()
        for fam in fam_list:
            file_obj.write(string.join(("[", fam, "]", "\n"),""))
            field_list = self.data[fam].keys()
            for field in field_list:
                file_obj.write(string.join((field, "=", self.data[fam][field], "\n"), ""))
            file_obj.write('\n')
        file_obj.close()    

    def copy(self):
        # Overriding UserDict for now with nothing...
        pass

if __name__ == '__main__':
    f = ini_file("spam.ini")
    print f["Spam"]["Eggs"]
    print f.GetProfileString("Spam", "Eggs")
    f.SetProfileString("Home", "Carrot", '"We are the knights who say Ni!"')
    # We have to do a manual save since autosave isn't set to 1...
    f.save()
        
